package util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Vector;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import model.Malote;

public class MaloteHandler
{
	private static final int TRANSFORMTOXMLBC = 0;

	private Vector<Malote> malotes;

	private String maloteContent;

	private String malotePath;

	private Communication communicator;

	public MaloteHandler(Communication communicator)
	{
		this.malotes = new Vector<Malote>();
		this.communicator = communicator;
	}

	public void generate()
	{
		try
		{

			File diretorio = new File("./");
			File todosArquivos[] = diretorio.listFiles();
			Malote temp;
			int posicao = -1;

			for (int i = 0; i < todosArquivos.length; i++)
			{
				String nomeArquivo = todosArquivos[i].getName();

				if (nomeArquivo.matches("(ch|doc)_[0-9]+_[0-9]+_[0-9]{8}.xml"))
				{
					String[] tokens = nomeArquivo.split("_");
					if (tokens.length == 4)
					{
						temp = new Malote();
						temp.setBancoEmissor(tokens[2]);

						posicao = this.malotes.indexOf(temp);

						if (posicao < 0)
						{
							this.malotes.add(temp);

							if (tokens[0].equals("ch"))
								temp.getCheques().add(nomeArquivo);
							else if (tokens[0].equals("doc"))
								temp.getDocs().add(nomeArquivo);

						} else
						{
							temp = this.malotes.get(posicao);

							if (tokens[0].equals("ch"))
								temp.getCheques().add(nomeArquivo);
							else if (tokens[0].equals("doc"))
								temp.getDocs().add(nomeArquivo);

						}
					}
				}

			}

		} catch (Exception e)
		{
			e.printStackTrace();
		}

	}

	public void compileAndTransform()
	{
		Iterator<Malote> it = this.malotes.iterator();
		FileHandler fileHandler = new FileHandler();
		StringBuffer stringBuffer = new StringBuffer();
		String conteudoTransformado;

		while (it.hasNext())
		{
			Malote m = it.next();
			stringBuffer = new StringBuffer();
			Vector<String> cheques = m.getCheques();

			stringBuffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<malote bancoOrigem=\"" + 4 + "\" bancoDestino=\"" + m.getBancoEmissor() + "\">\n");

			for (int i = 0; i < cheques.size(); i++)
			{
				String nomeArquivoCheque = cheques.elementAt(i);
				fileHandler.fileToString(nomeArquivoCheque, stringBuffer,true);
			}

			Vector<String> docs = m.getDocs();

			for (int i = 0; i < docs.size(); i++)
			{
				String nomeArquivoDoc = docs.elementAt(i);
				fileHandler.fileToString(nomeArquivoDoc, stringBuffer,true);
			}
			stringBuffer.append("</malote>\n");
		
			conteudoTransformado = transform(stringBuffer.toString(),MaloteHandler.TRANSFORMTOXMLBC, "malote.xml");
			m.setConteudoTransformado(conteudoTransformado);
			System.out.println("conteudoTransformado:\n" + m.getConteudoTransformado() + "\n");
		}

	}

	public String transform(String conteudo, int formatoTransformacao,String nomeArquivo)
	{
		String arquivoDeSaida = "malotebc.xml";
		File resultadoTransf = new File(arquivoDeSaida);
		File malote = new File(nomeArquivo);
		FileHandler fh = new FileHandler();
		try
		{
			resultadoTransf.createNewFile();
			malote.createNewFile();

			FileWriter writer = new FileWriter(malote);
			writer.write(conteudo);
			writer.close();
			
		} 
		catch (IOException e1)
		{
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		TransformerFactory tFactory = TransformerFactory.newInstance();
		Transformer transformer;
		StreamSource xslSource = null;
		StreamSource xmlSource = new StreamSource(malote);
		StreamResult xmlResult = null;
		
		try
		{
			xmlResult = new StreamResult(new FileOutputStream(resultadoTransf));
			
			if (formatoTransformacao == MaloteHandler.TRANSFORMTOXMLBC)
			{
				xslSource = new StreamSource(new File("src/xslt/bancoCentral.xsl"));
			}
			
			transformer = tFactory.newTransformer(xslSource);
			transformer.transform(xmlSource, xmlResult);

		} 
		catch (TransformerConfigurationException e)
		{
			e.printStackTrace();
		}
		catch (TransformerException e)
		{
			e.printStackTrace();
		} 
		catch (FileNotFoundException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return fh.fileToString(arquivoDeSaida,false);//trecho removido daqui
	}

	public void send()
	{
		Iterator<Malote> it = this.malotes.iterator();

		while (it.hasNext())
		{
			Malote m = it.next();
			String banco = m.getBancoEmissor();
			String conteudo = m.getConteudoTransformado();

			Scanner scanner = new Scanner(System.in);
			System.out.println("Informe o IP do banco '" + banco + "' : ");
			String ip = scanner.nextLine();
			System.out.println("Informe a porta de conexao do banco '" + banco	+ "' : ");
			int porta = scanner.nextInt();

			this.communicator.sendFile(conteudo, ip, porta);
		}
	}

	public Vector<Malote> getMalotes()
	{
		return malotes;
	}

	public void setMalotes(Vector<Malote> malotes)
	{
		this.malotes = malotes;
	}

	public String getMalotePath()
	{
		return malotePath;
	}

	public void setMalotePath(String malotePath)
	{
		this.malotePath = malotePath;
	}

	public String getMaloteContent()
	{
		return maloteContent;
	}

	public void setMaloteContent(String maloteContent)
	{
		this.maloteContent = maloteContent;
	}
}
